import {
  batchDelUserService,
  delUserService,
  getUserListService,
  UserData,
} from "@/services/api/userList";
import { useRequest } from "ahooks";
import {
  Button,
  Card,
  message,
  Modal,
  Pagination,
  Popconfirm,
  Space,
  Table,
  TableProps,
  Tag,
} from "antd";
import React, { useEffect, useRef, useState } from "react";
import SearchForm, { searchParam } from "../components/SearchForm";
import EditForm from "../components/EditForm";

const initPage = { pageNo: 1, pageSize: 10 };
const initSearch = {
  companyName: "",
  contact: "",
  tel: "",
};

const UserList: React.FC = () => {
  const [userList, setUserList] = useState<UserData[]>([]);
  const [selectedRowKeys, setSelectRowKeys] = useState<React.Key[]>([]);
  const [page, setPage] = useState(initPage);
  const [total, setTotal] = useState(0);
  const searchRef = useRef<searchParam>(initSearch);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modelTitle, setModelTitle] = useState("");
  const [editData, setEditData] = useState<Partial<UserData>>({});

  const { run, loading } = useRequest(getUserListService, {
    manual: true,
    onSuccess(data, params) {
      console.log("租户列表api", data, params);
      setUserList(data.list);
      setTotal(data.total);
    },
  });

  useEffect(() => {
    run({
      ...page,
      ...searchRef.current,
    });
  }, [page]);

  function searchData() {
    run({
      ...initPage,
      ...searchRef.current,
    });
    setPage(initPage);
  }

  function resetData() {
    setSelectRowKeys([]);
    setPage(initPage);
  }

  async function delData(id: string) {
    await delUserService(id);
    message.info("删除成功");
    run({ ...page, ...searchRef.current });
  }

  async function batchDelData(ids: React.Key[]) {
    await batchDelUserService(ids);
    message.info("删除成功");
    run({ ...page, ...searchRef.current });
  }

  const columns: TableProps<UserData>["columns"] = [
    {
      title: "No.",
      key: "index",
      render(value, record, index) {
        return index + 1;
      },
    },
    {
      title: "客户名称",
      key: "name",
      dataIndex: "name",
    },
    {
      title: "经营状态",
      key: "statue",
      dataIndex: "statue",
      render(value) {
        if (value === "1") return <Tag color="green">营业中</Tag>;
        if (value === "2") return <Tag color="#f50">暂停营业</Tag>;
        if (value === "3") return <Tag color="red">已关闭</Tag>;
      },
    },
    {
      title: "联系电话",
      key: "tel",
      dataIndex: "tel",
    },
    {
      title: "所属行业",
      key: "business",
      dataIndex: "business",
    },
    {
      title: "邮箱",
      key: "email",
      dataIndex: "email",
    },
    {
      title: "统一信用代码",
      key: "creditCode",
      dataIndex: "creditCode",
    },
    {
      title: "工商注册号",
      key: "industryNum",
      dataIndex: "industryNum",
    },
    {
      title: "组织结构代码",
      key: "organizationCode",
      dataIndex: "organizationCode",
    },
    {
      title: "法人名",
      key: "legalPerson",
      dataIndex: "legalPerson",
    },
    {
      title: "操作",
      key: "operate",
      render(value, record, index) {
        return (
          <>
            <Button size="small" type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Popconfirm
              title="删除数据"
              description="确认删除该条用户信息？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => delData(record.id)}
            >
              <Button size="small" type="link" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  function selectChange(selectedRowKeys: React.Key[]) {
    console.log(selectedRowKeys);
    setSelectRowKeys(selectedRowKeys);
  }

  function pageChange(pageNo: number, pageSize: number) {
    setPage({ pageNo, pageSize });
  }

  const handleOk = () => {
    setIsModalOpen(false);
    setEditData({});
    run({
      ...page,
      ...searchRef.current,
    });
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setEditData({});
  };

  const handleAdd = () => {
    setModelTitle("新增数据");
    setIsModalOpen(true);
    setEditData({});
  };

  const handleEdit = (record: UserData) => {
    setModelTitle("修改数据");
    setIsModalOpen(true);
    setEditData(record);
  };

  return (
    <div>
      <Space className="fx" direction="vertical" size="large">
        {/* 查询表单 */}
        <Card>
          <SearchForm
            ref={searchRef}
            searchData={searchData}
            resetData={resetData}
          />
        </Card>
        {/* 表格展示 */}
        <Card
          title="租户明细表"
          extra={
            <Space size="middle">
              <Button type="primary" onClick={handleAdd}>
                新增企业
              </Button>
              <Popconfirm
                title="删除数据"
                description="确认删除批量删除选中数据？"
                okText="确认"
                cancelText="取消"
                onConfirm={() => batchDelData(selectedRowKeys)}
              >
                <Button
                  type="primary"
                  danger
                  disabled={!selectedRowKeys.length}
                >
                  批量删除
                </Button>
              </Popconfirm>
            </Space>
          }
        >
          <Table
            columns={columns}
            dataSource={userList}
            rowKey={(record) => record.id}
            loading={loading}
            pagination={false}
            rowSelection={{
              selectedRowKeys,
              onChange: selectChange,
            }}
          />
          <Pagination
            style={{ marginTop: "12px" }}
            showQuickJumper
            align="end"
            total={total}
            current={page.pageNo}
            pageSize={page.pageSize}
            showTotal={(total) => `共 ${total} 条`}
            onChange={pageChange}
          />
        </Card>
      </Space>
      {/* 编辑表单 */}
      <Modal
        title={modelTitle}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <EditForm data={editData} onSubmit={handleOk} />
      </Modal>
    </div>
  );
};

export default UserList;
